//
//  LJHomeViewController.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/15.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
import SVPullToRefresh

enum LJStatusCellReuseIdentifier: String {
    case StatusNormalCell = "StatusNormalCell"
    case StatusForwardCell = "StatusForwardCell"
}

class LJHomeViewController: LJBaseViewController {
    /// 重用标示
//    private let ReuseIdentifier = "LJStatusCell"
    /// 模型数组
    var statuses: [LJStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    
    private let tipLabelHeight: CGFloat = 44
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !LJUserAccount.isUserLogin{
            return
        }
        // 设置导航栏
        setupNav()
        
        // 设置tableView
        setupTableView()
        
        // 设置上拉刷新控件
        refreshControl = LJRefreshControl()
        
        // 设置监听事件
        refreshControl?.addTarget(self, action: "loadNewStatus", forControlEvents: UIControlEvents.ValueChanged)
        
        // 加载数据
//        loadStatus()
        
        // 主动进入刷新状态
        refreshControl?.beginRefreshing()
        // 手动触发监听事件
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        
        // 监听图片被点击事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "pictureDidSelected:", name: LJStatusPictureViewCellDidSelectNotication, object: nil)
        
    }
    
    // 取消监听
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 通知回调方法
    @objc func pictureDidSelected(notication: NSNotification) {
        guard let indexPath = notication.userInfo?[LJStatusPictureViewCellDidSelectIndexPathKey] as? NSIndexPath else {
            print("indexPath为空")
            return
        }
        guard let largeURLs = notication.userInfo?[LJStatusPictureViewCellDidSelectURLKey] as? [NSURL] else {
            print("图片URL数组为空")
            return
        }
        
        let pictureBroserVC = LJPhotoBrowserController(indexPath: indexPath, URLs: largeURLs)
        self.presentViewController(pictureBroserVC, animated: false, completion: nil)
    }
    
    /// 加载数据方法
    func loadNewStatus() {
        let since_id = statuses?.first?.id ?? 0
        let max_id = 0
        LJStatus.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            // 拿到数据则关闭刷新控件
            self.refreshControl?.endRefreshing()
            
            let count = statuses?.count ?? 0
            
            if error != nil || statuses == nil{
                print("错误:\(error)")
                return
            }
            
            if since_id > 0 {
                self.showTipLabel(count)
            }
            
            if count == 0 {
                print("没有最新数据")
                return
            }
            if since_id > 0 {
                self.statuses = statuses! + self.statuses!
            }else{
                self.statuses = statuses
                // 显示菊花
                self.tableView.showsInfiniteScrolling = true
            }
        }
    }
    
    // 加载更多数据
    func loadMoreStatus() {
        let since_id = 0
        let max_id = statuses?.last?.id ?? 0
        LJStatus.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            // 关闭菊花
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil || statuses == nil {
                print("加载更多微博出错\(error)")
                return
            }
            if statuses!.count == 0 {
                print("没有更多数据")
                return
            }
            if max_id > 0 {
                self.statuses = self.statuses! + statuses!
            }
            
        }
    }
    
    // MARK: - 设置导航栏
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        let title = LJUserAccount.loadUserAccount()?.screen_name ?? "没有获取到用户名"
        let titleButton = LJHomeTitleView(imageName: "navigationbar_arrow_up", title: title)
        navigationItem.titleView = titleButton
        titleButton.addTarget(self, action: "titleViewDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
    }
    /// 导航栏顶部View被点击时调用的方法
    @objc private func titleViewDidClick(button: UIButton){
        button.selected = !button.selected
        // 动画
        UIView.animateWithDuration(0.25) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.0001)) : CGAffineTransformIdentity
        }
    }
    
    // 设置tableView
    private func setupTableView(){
        /// 设置行高
        tableView.estimatedRowHeight = 200
        
        // 设置cell分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 注册cell
        tableView.registerClass(LJStatusForwardCell.self, forCellReuseIdentifier: LJStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        tableView.registerClass(LJStatusNormalCell.self, forCellReuseIdentifier: LJStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        
        // 设置上拉刷新
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatus()
        }
        // 先不显示菊花
        tableView.showsInfiniteScrolling = false
    }
    
    // 展示提示控件
    private func showTipLabel(count: Int) {
        tipLabel.text = count == 0 ? "没有加载到新的微博数据" : "加载了\(count)条微博数据"
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        UIView.animateWithDuration(1.25, animations: { () -> Void in
            self.tipLabel.frame.origin.y = self.tipLabelHeight
            }) { (_) -> Void in
                UIView.animateKeyframesWithDuration(1.25, delay: 0.25, options: UIViewKeyframeAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -(self.tipLabelHeight + 20)
                    }, completion: nil)
        }
    }

    // MARK: - TableView 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        let reuseID = status.cellID()
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID) as! LJStatusCell
        cell.status = status
        
        return cell
        
    }

   /// MARK: - tableView代理方法
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 获取当前模型数据
        let status = statuses![indexPath.row]
        if status.rowHeight != nil {
            // 有缓存的行高
//            print("缓存rowheight\(status.rowHeight)")
            return status.rowHeight!
        }
        let reuseID = status.cellID()
        // 获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID) as! LJStatusCell
        // 计算行高
        let rowheight = cell.rowHeight(status)
        // 保存行高
        status.rowHeight = rowheight
//        print("计算rowheight\(rowheight)")
        return rowheight
    }
    
    // MARK: - 懒加载
    private lazy var tipLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: -(self.tipLabelHeight + 20), width: UIScreen.mainScreen().bounds.width, height: self.tipLabelHeight))
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.font = UIFont.systemFontOfSize(14)
        return label
    }()
}
